/*项目地址*/
const app = '/lesson-admin';

onload = () => {
    // 将sessionStorage中存储的用户数据取出来
    let user = JSON.parse(sessionStorage.getItem('user'));

    // 将用户的数据赋值到表单的对应控件中
    initForm(user);

    // 给修改按钮挂载点击事件
    document.querySelector('#updateBtn').onclick = () => {
        console.log("进入修改程序");
        updateUser(user['user-id']);

    };
};

/*将用户的数据赋值到表单的对应控件中*/
function initForm(user) {
    // 对位赋值
    document.querySelector('#usernameIpt').value = user['username'];
    document.querySelector('#passwordIpt').value = user['password'];
    document.querySelector('#realNameIpt').value = user['real-name'];
    document.querySelector('#nickNameIpt').value = user['nick-name'];
    document.querySelector('#ageIpt').value = user['age'];
    document.querySelector('#idCardIpt').value = user['id-card'];
    document.querySelector('#phoneIpt').value = user['phone'];
    document.querySelector('#userInfoArea').value = user['user-info'];
    document.querySelector('#createTimeIpt').value = user['create-time'];
    document.querySelector('#modifyTimeIpt').value = user['modify-time'];
    // 对性别进行赋值
    let gender = user['gender'];
    if (gender === 0) {
        document.querySelector('#gender0').setAttribute('checked', 'checked');
    } else if (gender === 1) {
        document.querySelector('#gender1').setAttribute('checked', 'checked');
    } else {
        document.querySelector('#gender2').setAttribute('checked', 'checked');
    }
}

/*修改一条用户记录*/
function updateUser(userId) {

    // 准备请求参数
    let password = document.querySelector('#passwordIpt').value;
    let nickName = document.querySelector('#nickNameIpt').value;
    let gender = document.querySelector('input[name=gender]:checked').value;
    let age = document.querySelector('#ageIpt').value;
    let phone = document.querySelector('#phoneIpt').value;
    let userInfo = document.querySelector('#userInfoArea').value;
    let createTime = document.querySelector('#createTimeIpt').value;

    // 判断必要参数不为空
    if (userId && password && nickName && gender && age && phone
        && userInfo && createTime) {

        // 处理日期格式: 2023-08-12T15.26  -> 2020-02-01 12:12:12
        createTime = createTime.replace('T', ' ').replace('.', ':') + ':00';

        // 发送添加用户请求
        ajax({
            'url': app + `/api/v1/user/update-by-user-id`,
            'type': 'post',
            'contentType': 'json',
            'data': {
                "password": password, "nick-name": nickName, "gender": gender,
                "age": age, "phone": phone, "user-info": userInfo,
                "create-time": createTime, "user-id": userId
            },
            'success': res => {
                // 修改失败
                if (res.code < 1) alert(res.message);
                // 修改成功
                else {
                    alert('修改成功!')
                    location.href = '../user/user.html';
                }
            }
        });
    } else {
        alert('必要填写项为空，请检查！')
    }
}